import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))

from fastapi import FastAPI
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langserve import add_routes
from config_reader import get_langserver_config, get_openai_api_key, get_langsmith_config

# 获取配置
langserver_config = get_langserver_config()
openai_api_key = get_openai_api_key()
langsmith_config = get_langsmith_config()

# 设置代理
os.environ['http_proxy'] = f"{langserver_config['proxy_host']}:{langserver_config['proxy_port']}"
os.environ['https_proxy'] = f"{langserver_config['proxy_host']}:{langserver_config['proxy_port']}"

# 设置LangSmith配置
os.environ["LANGCHAIN_TRACING_V2"] = langsmith_config['tracing_v2']
os.environ["LANGCHAIN_ENDPOINT"] = langsmith_config['endpoint']
os.environ["LANGCHAIN_PROJECT"] = langsmith_config['project']
os.environ["LANGCHAIN_API_KEY"] = langsmith_config['api_key']

# 设置OpenAI API密钥
os.environ["OPENAI_API_KEY"] = openai_api_key

# 调用大语言模型
# 创建模型
model = ChatOpenAI(model=langserver_config['model_name'])

# 2、准备prompt
msg = [
    SystemMessage(content='请将以下的内容翻译成意大利语'),
    HumanMessage(content='你好，请问你要去哪里？')
]

# result = model.invoke(msg)
# print(result)

# 简单的解析响应数据
# 3、创建返回的数据解析器
parser = StrOutputParser()
# print(parser.invoke(result))


# 定义提示模板
prompt_template = ChatPromptTemplate.from_messages([
    ('system', '请将下面的内容翻译成{language}'),
    ('user', "{text}")
])

# 4、得到链
chain = prompt_template | model | parser

# 5、 直接使用chain来调用
# print(chain.invoke(msg))
print(chain.invoke({'language': 'English', 'text': '我下午还有一节课，不能去打球了。'}))


# 把我们的程序部署成服务
# 创建fastAPI的应用
app = FastAPI(
    title=langserver_config['app_title'], 
    version=langserver_config['app_version'], 
    description=langserver_config['app_description']
)

add_routes(
    app,
    chain,
    path=langserver_config['chain_path'],
)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host=langserver_config['host'], port=langserver_config['port'])